package com.sgb.kjwl.viewmodel.home;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.view.entity.EnterpriseEditEntity;
import com.swgk.core.view.entity.HomeManageMenuEntity;
import com.sgb.kjwl.model.entity.home.MenuManageEntity;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.service.MailListAPI;
import com.sgb.kjwl.model.entity.BannerEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.view.entity.MenuEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.ProvinceEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.businessmanagement.CompanyEntity;
import com.sgb.kjwl.model.entity.user.EssentiaIinformationeEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.utils.UserInfoCacheUtils;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.MainRecruitmentFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainRecruitmentModel extends BaseViewModel {
    private HomeRepertory repertory;
    private MainRecruitmentFragment fragment;

    public MainRecruitmentModel(MainRecruitmentFragment fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    //获取所有省、自治区、直辖市
    public void getLocalProvince() {
        APIManager.getInstance().getCommonAPI().getCurrentArea().enqueue(new ICallBack<BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>> data) {
                if (data.getData() == null)
                    return;
                List<ProvinceEntity<List<ProvinceEntity>>> provinceEntityList = data.getData();
//                        android 24 以下不能使用此方法
/*
                        List<ProvinceEntity<List<ProvinceEntity>>> groups = provinceEntityList.stream()
                                .filter((obj ->(obj.isChecked()==true)))
                                .collect(Collectors.toList());
*/

                for (ProvinceEntity<List<ProvinceEntity>> provinceEntity : provinceEntityList) {
                    if (provinceEntity.isChecked() == true) {
                        Log.d("选中的城市", provinceEntity.getAreaName());
                        if (Integer.parseInt(repertory.getAreaCode()) != provinceEntity.getId()) {
                            fragment.showChangeDialog(provinceEntity);
                        }
                        //把选中的城市id保存在本地
//                                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PROVINCE_ID,provinceEntity.getId());
                        return;
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>>> call, Throwable t) {

            }
        });


//        repertory.getAllProvince()
//                .subscribe(new Consumer<BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>>>() {
//                    @Override
//                    public void accept(BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>> listBaseEntity) throws Exception {
//                        List<ProvinceEntity<List<ProvinceEntity>>> provinceEntityList = listBaseEntity.getData();
////                        android 24 以下不能使用此方法
///*
//                        List<ProvinceEntity<List<ProvinceEntity>>> groups = provinceEntityList.stream()
//                                .filter((obj ->(obj.isChecked()==true)))
//                                .collect(Collectors.toList());
//*/
//
//                        for (ProvinceEntity<List<ProvinceEntity>> provinceEntity : provinceEntityList) {
//                            if (provinceEntity.isChecked() == true) {
//                                Log.d("选中的城市", provinceEntity.getAreaName());
//                                if (Integer.parseInt(repertory.getAreaCode()) != provinceEntity.getId()) {
//                                    fragment.showChangeDialog(provinceEntity);
//                                }
//                                //把选中的城市id保存在本地
////                                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PROVINCE_ID,provinceEntity.getId());
//                                return;
//                            }
//                        }
//
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        MLog.d(AppConstant.API_LOG, throwable.getMessage());
//                    }
//                });
    }

    public String getAreaNameModel() {
        String name = repertory.getAreaName();
        if (!name.contains("省")) {
            name = name.substring(0, 2);
        }
        return name;
    }

    //首页banner
    public void getBannerModel() {
//            DialogHelper.showProgressDialog(fragment.getContext(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getRecruitmentHomeAPI().getBanner().enqueue(new ICallBack<BaseEntity<List<BannerEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<BannerEntity>> data) {
                DialogHelper.dismissProgressDialog();
                if (data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showBannerView(data.getData());
                } else {
                    MToast.showToast(fragment.getContext(), data.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<BannerEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //首页menu
    public void getMenuModel() {
        String json = MkvUtils.get().getString(MkvUtils.CacheModular, CacheMarker.BiddingMenu, "");
        if (!TextUtils.isEmpty(json)) {
            List<MenuEntity> data = new Gson().fromJson(json, new TypeToken<List<MenuEntity>>() {
            }.getType());
//            fragment.showMenuView(data);
        }

        APIManager.getInstance().getRecruitmentHomeAPI().getCategory().enqueue(new ICallBack<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity>> data) {
                if (data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    if (data.getData() != null) {
                        //获取从网络请求下来的数据的哈希值
//                        String dataJson = DatalUtils.getInstance().getJsonString(data.getData());
//                        String mHashNet = DatalUtils.strToHashKey(dataJson);
//                        String hashData = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.BiddingMenu);
                        boolean isEqual = DatalUtils.getInstance().IsCahceEqual(data.getData(), CacheMarker.BiddingMenu);

                        if (!isEqual) {
//                            fragment.showMenuView(data.getData());
//                            MkvUtils.get().putString(MkvUtils.CacheModular, CacheMarker.BiddingMenu, dataJson);
                        }
                    }

                } else {
                    MToast.showToast(fragment.getContext(), data.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<MenuEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //首页推荐列表
//    public void getRecommendListModel() {
//        DialogHelper.showProgressDialog(fragment.getContext(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
//        APIManager.getInstance().getRecruitmentHomeAPI().getInquiryCenter().enqueue(new ICallBack<BaseEntity<List<MaterialMenuEntity>>>() {
//            @Override
//            public void onSuccess(BaseEntity<List<MaterialMenuEntity>> data) {
//                DialogHelper.dismissProgressDialog();
//                if (data.getState() == null){
//                    return;
//                }
//                if (data.getState().equals(APIManager.RESPONSE_OK)) {
//                    fragment.showRecommendList(data.getData());
//                } else {
//                    MToast.showToast(fragment.getContext(), data.getMsg());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<BaseEntity<List<MaterialMenuEntity>>> call, Throwable t) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
//    }

    public void saveProvinceModel(String name, String code) {
        repertory.setAreaCode(code);
        repertory.setAreaName(name);
    }

    public void getFilterTypeData() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(fragment.getContext(), "获取信息中...");
        }
        APIManager.getInstance().getPickAPI().tenderNewTypeList().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setTypeData(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getFilterPickInfoTypeData() {
        Map map = new HashMap();
        map.put("areacode", repertory.getAreaCode());
        map.put("keyword", "");
        map.put("name", "");
        APIManager.getInstance().getPickAPI().getPickInfoType(map).enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setTypePickInfoData(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {

            }
        });
    }

    /**
     * 通过标识来获取跳转连接
     */
    public void getStringUrl(String param,String urlId) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting(param).enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + urlId;
                    WebViewX5HostActivity.start(fragment.getActivity(), url);
                }
            }
        });
    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "登录中", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(fragment.getContext(), SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        fragment.getContext().startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(fragment.getContext(), "登录成功");
                fragment.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(fragment.getContext(), 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    fragment.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(fragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }

    //新增类型过滤接口
    public void getTenderGoodsCategoryAllList(String category) {
        if (fragment.getActivity() != null && !fragment.getActivity().isDestroyed() && !fragment.getActivity().isFinishing()){
            DialogHelper.showProgressDialog(fragment.getActivity(), null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        }
        Map map = new HashMap();
        map.put("type", category);
        APIManager.getInstance().getPickAPI().getTenderGoodsCategoryAllList(map).enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setTenderGoodsCategoryAllList(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
//
//    /**
//     * 公司列表信息
//     */
//    public void getCompanyList() {
//        DialogHelper.showProgressDialog(fragment.getContext(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
//        APIManager.getInstance().getMailListAPI().getUserCompany(MailListAPI.UserCenterUrl.URL_GET_USER_COMPANY).enqueue(new Callback<BaseEntity<List<CompanyEntity>>>() {
//            @Override
//            public void onResponse(Call<BaseEntity<List<CompanyEntity>>> call, Response<BaseEntity<List<CompanyEntity>>> response) {
//                if (response.body() == null) return;
//                if (response.body().getState().equals("ok")) {
//                    fragment.showCompanyList(response.body().getData());
//                }
//            }
//
//            @Override
//            public void onFailure(Call<BaseEntity<List<CompanyEntity>>> call, Throwable t) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
//    }

//    /**
//     * 设置主企业
//     *
//     * @param companyEntity
//     */
//    public void settingMainCompany(CompanyEntity companyEntity) {
////        DialogHelper.showProgressDialog(fragment.getContext(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
//        APIManager.getInstance().getMailListAPI().settingMainCompany(companyEntity.getCompNo(), companyEntity.getType()).enqueue(
//                new ICallBack<BaseEntity<LoginEntity>>() {
//                    @Override
//                    public void onSuccess(BaseEntity<LoginEntity> data) {
////                DialogHelper.dismissProgressDialog();
//                        if (data == null) return;
//                        if (data.getState() == null) return;
//                        if (data.getState().equals("ok")) {
//                            // 保存 token
//                            LoginEntity entity = data.getData();
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, entity.getResourcePCToken());
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, entity.getResourceAPPToken());
//                            //给SharedPreferenceUtil中的COMPANY_NO赋值 保存公司ID
//                            Log.e("公司no", companyEntity.getCompNo());
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NO, companyEntity.getCompNo());
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ENTERPRISE_NO, companyEntity.getCompNo());
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NAME, companyEntity.getCompName());
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMP_LOGO, companyEntity.getCompLogo());
//                            //查询个人中心商品列表
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.REAL_ID, companyEntity.getCompanyId());
//                            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, companyEntity.getType());
//                            repertory.saveToken(entity.getToken());
//                            fragment.setCurrentCompany(companyEntity);
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
//                        DialogHelper.dismissProgressDialog();
//                    }
//                });
//    }


//    /**
//     * 获取用户的基本信息
//     */
//    public void getEssentialInformation(CompanyEntity companyEntity) {
//        APIManager.getInstance().getUserAPI().getEssential_information(companyEntity.getCompNo(), String.valueOf(companyEntity.getType())).enqueue(new Callback<BaseEntity<EssentiaIinformationeEntity>>() {
//            @Override
//            public void onResponse(Call<BaseEntity<EssentiaIinformationeEntity>> call, Response<BaseEntity<EssentiaIinformationeEntity>> response) {
//                if (response.body() == null) {
//                    return;
//                }
//                if (response.body().getData() != null) {
//                    String CacheMateialistlHash = DatalUtils.getHashData(MkvUtils.get().CommomData, CacheMarker.CacheUserInfo);
//                    Gson gson = new Gson();
//                    //获取从网络请求下来的数据的哈希值
//                    String data1 = gson.toJson(response.body().getData());
//                    String mHashNet = DatalUtils.strToHashKey(data1);
//                    //临时关闭团队类型展示
//                    //fragment.showHeadPortrait(response.body().getData());
//                    if (!CacheMateialistlHash.equals(mHashNet)) {
//                        //存储用户的基本信息
//                        UserInfoCacheUtils.setUserInfoData(response.body().getData());
//                    }
//                }
//            }
//
//            @Override
//            public void onFailure(Call<BaseEntity<EssentiaIinformationeEntity>> call, Throwable t) {
//            }
//        });
//    }

    /**
     * 新金刚区列表数据
     **/
    public void getPickMenuList() {
        APIManager.getInstance().getBigHomeAPI().getHomeMenuList("zhaoCai").enqueue(new ICallBack<BaseEntity<MenuManageEntity<List<HomeManageMenuEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<MenuManageEntity<List<HomeManageMenuEntity>>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showMenuView(data.getData());
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    int i = 0;
    /**
     * 根据用户身份信息获取展示的企业标题
     */
    public void getCompanyTitleList(String areaCode) {
        i++;
        areaCode = repertory.getAreaCode();
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.AREA_CODE, repertory.getAreaCode());
        int code = TextUtils.isEmpty(areaCode)?615000:Integer.valueOf(areaCode);
        APIManager.getInstance().getBigHomeAPI().getEnterpriseRecListNew(code).enqueue(new ICallBack<BaseEntity<List<EnterpriseEditEntity>>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<List<EnterpriseEditEntity>> data) {
                i = 0;
                fragment.initCompanyTitle(data.getData());
            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                super.onFailureSwitchErrCode(entity);
                if (entity != null && i<2){
                    if ("53999".equals(entity.getErrCode())){
                        getCompanyTitleList("");
                    }
                }
            }
        });
    }
}
